package site.syksy.qingzhou.security.authentication;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import site.syksy.qingzhou.security.domain.GeneralLoginVO;
import site.syksy.qingzhou.upms.service.UserService;

import java.util.Map;

/**
 * @author Raspberry
 */
public class GeneralAuthenticationProvider implements AuthenticationProvider {

    private UserService userService;

    private PasswordEncoder passwordEncoder;

    public GeneralAuthenticationProvider(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        GeneralLoginVO generalLoginVO = (GeneralLoginVO) authentication.getCredentials();
        Map<String,String> userMap = userService.getUserMapByUsername(generalLoginVO.getUsername());
        String encodedPassword = userMap.get("password");
        if (StringUtils.isBlank(encodedPassword)) {
            throw new AuthenticationServiceException("账户不存在");
        }
        if (!passwordEncoder.matches(generalLoginVO.getPassword(), encodedPassword)) {
            throw new AuthenticationServiceException("密码错误");
        }
        generalLoginVO.setUserId(userMap.get("userId"));
        return new GeneralAuthenticationToken(null, generalLoginVO);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        if (authentication.equals(GeneralAuthenticationToken.class)) {
            return true;
        } else {
            return false;
        }
    }
}
